import time  
  
class PID:  
    def __init__(self, kp, ki, kd, setpoint, sample_time):  
        self.kp = kp  # 比例系数  
        self.ki = ki  # 积分系数  
        self.kd = kd  # 微分系数  
        self.setpoint = setpoint  # 目标值  
        self.sample_time = sample_time  # 采样时间  
  
        self._last_error = 0  
        self._integral = 0  
        self._last_time = time.perf_counter()  
  
    def update(self, measured_value):  
        current_time = time.perf_counter()  
        delta_time = current_time - self._last_time  
  
        error = self.setpoint - measured_value  
        self._integral += error * delta_time  
        derivative = (error - self._last_error) / delta_time if delta_time != 0 else 0  
  
        output = (self.kp * error) + (self.ki * self._integral) + (self.kd * derivative)  
  
        self._last_error = error  
        self._last_time = current_time  
  
        return output  
  
# PID参数  
kp = 1.0  
ki = 0.1  
kd = 0.01  
setpoint = 100.0  
sample_time = 0.1  # 采样时间，单位为秒  
  
# 创建PID控制器实例  
pid = PID(kp, ki, kd, setpoint, sample_time)  
  
# 模拟测量值  
measured_value = 90.0  
  
# 测量单步运算耗时  
start_time = time.perf_counter()  
output = pid.update(measured_value)  
end_time = time.perf_counter()  
  
elapsed_time = end_time - start_time  
print(f"PID单步运算耗时: {elapsed_time * 1000:.6f} 毫秒")